package xyz.liut.liutlibraries;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;

import cz.msebera.android.httpclient.Header;

public class UploadFile {

    private static final String TAG = "UploadFile";
    private static Gson gson = new Gson();


    //上传单文件
    public static void uploadFile(File file, String url, final Context mContext) {

        if (file.exists() && file.length() > 0) {
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            try {
                params.put("uploadfile", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 上传文件
            client.post(url, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                    ResultsEntity entity = gson.fromJson(new String(responseBody), new TypeToken<ResultsEntity>() {
//                    }.getType());
//                    Toast.makeText(mContext, entity.getMessage(), Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Toast.makeText(mContext, "上传失败" + error.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e(TAG, "onFailure: " + error.getMessage());
                }

            });
        } else {
            Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
        }

    }


    //上传3文件
    public static void uploadFiles(File file1, File file2, File file3, String url, final Context mContext,AsyncHttpResponseHandler responseHandler) {

        Log.e(TAG, "uploadFiles: "+url );

        if (file1.exists() && file1.length() > 0) {
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            try {
                params.put("uploadfile[1]", file1);
                params.put("uploadfile[2]", file2);
                params.put("uploadfile[3]", file3);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 上传文件
            client.post(url, params, responseHandler);
        } else {
            Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
        }

    }

}